<template>
  <div class="detail">
    <div>
      <!-- 介绍 -->
      <div class="introduction">
        <div class="title">
          <div></div>
          {{ propsData.contentName.split(" ")[1] }}
          <div class="tag">
            <img src="@/assets/icon/type.png" />
            {{ propsData.contentType }}
          </div>
          <div class="tag">
            <img src="@/assets/icon/author.png" />
            {{ propsData.contentAuthor }}
          </div>
          <div class="tag" v-show="propsData.contentType === 'face'">
            <img src="@/assets/icon/num.png" />
            {{ propsData.contentName.substring(0, 4) }}
          </div>
        </div>
      </div>
      <!-- 图片 -->
      <div class="pic">
        <!-- 操作按钮 -->
        <div class="controller" @click="confirm">
          <img src="@/assets/other/打勾.png" />
        </div>
        <img :src="picUrl" :id="picType" @load="picOnLoad" />
      </div>
      <!-- 弃用与删除Mod -->
      <div class="ModController">
        <!-- 停用Mod -->
        <div class="abandonModRun" @click="abandonModRun">
          <el-tooltip
            class="box-item"
            effect="light"
            content="从游戏中停用此Mod"
            placement="top-start"
          >
            <el-button>
              <img src="@/assets/other/弃用.png" />
              <span>停用</span>
            </el-button>
          </el-tooltip>
        </div>
        <!-- 删除Mod -->
        <div class="deleteModRun" @click="deleteModRun">
          <el-tooltip
            class="box-item"
            effect="light"
            content="从数据包中删除此Mod"
            placement="top-start"
          >
            <el-button>
              <img src="@/assets/other/删除.png" />
              <span>删除</span>
            </el-button>
          </el-tooltip>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/*eslint-disable*/
import { getCurrentInstance, onMounted } from "vue";
import mainApi from "@/api/mainApi";
import { ElMessage, ElMessageBox } from "element-plus";
import pubsub from "pubsub-js";

export default {
  name: "detail",
  props: {
    propsData: {
      type: Object,
      default: "",
    },
  },
  data() {
    return {
      picUrl: "",
      picType: "",
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    let fileHousePath = "";
    let fs = window.myApi.fs,
      path = window.myApi.path;

    onMounted(() => {
      mainApi.readJson(ElMessage, (data) => {
        console.log(proxy.propsData);
        fileHousePath = data.fileHouse;
        mainApi.writeDailyLog(
          "读取文件仓库路径" + data.fileHouse + "--detail.vue"
        );

        // 遍历文件路径
        traverseDirectory(
          window.myApi.path.join(
            data.fileHouse,
            proxy.propsData.contentType,
            // 面补特殊处理
            proxy.propsData.contentType === "face"
              ? proxy.propsData.contentName.match(/\d{4}/)[0]
              : "",
            proxy.propsData.contentName
          ),
          (pic) => {
            proxy.picUrl = pic;
          }
        );
      });
    });

    // 文件读取
    function traverseDirectory(folderPath, fun) {
      let fs = window.myApi.fs;
      let path = window.myApi.path;

      if (!fs.existsSync(folderPath)) {
        console.log("文件夹不存在:", folderPath);
        mainApi.writeDailyLog("文件夹不存在:" + folderPath + "--detail.vue");
        return;
      }

      // console.log(files);
      // 遍历文件夹内容
      let fullPath = path.join(folderPath, "preview");
      // 图片路径
      fullPath = path.join(fullPath, fs.readdirSync(fullPath)[0]);

      // 读取图片为base64
      fs.readFile(fullPath, { encoding: "base64" }, (err, imageData) => {
        if (err) {
          ElMessage({
            message: `[${file}]图片读取失败`,
            type: "error",
            duration: 10000,
          });
          mainApi.writeDailyLog(
            ` ${file}图片读取失败:` + fullPath + "--detail.vue"
          );
          throw err;
        }

        // 载入内容
        fun(`data:image/jpeg;base64,${imageData}`);
      });
    }

    // 确认替换
    function confirm() {
      mainApi.readJson(ElMessage, (data) => {
        // 文件仓库(面补类型特殊处理)
        let filePath =
          data.fileHouse +
          proxy.propsData.contentType +
          "\\" +
          (proxy.propsData.contentType === "face"
            ? `${proxy.propsData.contentName.split("-")[0]}\\`
            : "") +
          proxy.propsData.contentName;
        mainApi.writeDailyLog("执行替换:" + filePath + "--detail.vue");
        // 执行替换
        let modName =
          proxy.propsData.contentType === "face"
            ? proxy.propsData.contentName
            : proxy.propsData.contentName.split(" ")[1];
        mainApi.modReplace(filePath, modName);
        // console.log(filePath, proxy.propsData.contentName.split(" ")[1]);
      });
    }

    // 弃用Mod总起
    function abandonModRun() {
      // 文件路径拼串
      let faceSetFolder =
        proxy.propsData.contentType === "face"
          ? proxy.propsData.contentName.split("-")[0]
          : null;
      let filePath = path.join(
        fileHousePath,
        proxy.propsData.contentType,
        faceSetFolder,
        proxy.propsData.contentName
      );
      console.log(filePath);
      // 询问
      ElMessageBox.confirm("是否确认停用Mod", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          fs.readdirSync(filePath).forEach((element) => {
            // 不处理preview文件夹
            if (element != "preview") {
              // iff文件处理
              if (element.split(".")[1] === "iff") {
                abandonMod(element);
              }
              // 文件夹处理
              else {
                fs.readdirSync(path.join(filePath, element)).forEach(
                  (element2) => {
                    abandonMod(path.join(element, element2));
                  }
                );
              }
            }
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
        });
    }

    // 弃用Mod执行
    function abandonMod(modName) {
      mainApi.readJson(ElMessage, (data) => {
        // mod路径拼接
        let modPath = path.join(data.waigua, modName);
        mainApi.writeDailyLog("执行删除:" + modPath + "--detail.vue");
        // 判断mod文件是否存在
        fs.access(modPath, fs.constants.F_OK, (err) => {
          if (err) {
            ElMessage({ message: modName + "不存在", type: "error" });
            mainApi.writeDailyLog("待删文件不存在:" + modPath + "--detail.vue");
          } else {
            // 删除
            fs.unlink(modPath, (err) => {
              if (err) {
                ElMessage({ message: "删除失败" + err, type: "error" });
                mainApi.writeDailyLog("删除失败:" + err + "--detail.vue");
              } else {
                ElMessage({ message: modName + "删除成功" });
                mainApi.writeDailyLog("删除成功:" + modPath + "--detail.vue");
              }
            });
          }
        });
      });
    }

    // 删除Mod总起
    function deleteModRun() {
      ElMessageBox.confirm("是否确认删除Mod", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 文件路径拼串
          let faceSetFolder =
            proxy.propsData.contentType === "face"
              ? proxy.propsData.contentName.split("-")[0]
              : null;
          let filePath = path.join(
            fileHousePath,
            proxy.propsData.contentType,
            faceSetFolder,
            proxy.propsData.contentName
          );
          // 执行删除
          deleteMod(filePath);
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消",
          });
        });
    }

    // 删除Mod执行
    function deleteMod(modPath) {
      fs.rm(modPath, { recursive: true }, (err) => {
        if (err) {
          ElMessage({
            message: "删除失败" + err,
            type: "error",
            duration: 10000,
          });
          mainApi.writeDailyLog("删除失败:" + err + "--detail.vue");
        } else {
          ElMessage({ message: modPath + "删除成功" });
          mainApi.writeDailyLog("删除成功:" + modPath + "--detail.vue");
          // 面补集检查
          if (modPath.indexOf("face") != -1) faceSetReview(modPath);
          // 返回上一级路径
          let fatherPath =
            proxy.propsData.origin_nav === "faceSet"
              ? "face"
              : proxy.propsData.origin_nav;
          pubsub.publish("routerChange", {
            targetComponent: fatherPath,
            linkName: fatherPath,
            componentName: fatherPath,
            origin_nav: "Nav",
            isNav: true,
          });
        }
      });
    }

    // 面补集文件夹删除
    function faceSetReview(modPath) {
      // 面补集文件夹路径获取
      let faceSetPath = path.resolve(modPath, "..");
      fs.readdir(faceSetPath, (err, files) => {
        if (err) {
          return console.error("读取文件夹时出错:", err);
        }
        // 检查文件夹是否为空
        if (files.length === 0) {
          // 文件夹为空，可以删除
          fs.rmdir(faceSetPath, (err) => {
            if (err) {
              mainApi.writeDailyLog(
                faceSetPath + "删除文件夹时出错:" + err + "--detail.vue"
              );
              return;
            }
            // 正常删除
            ElMessage({ message: faceSetPath + "空文件夹已删除" });
            mainApi.writeDailyLog(
              "空文件夹已删除:" + faceSetPath + "--detail.vue"
            );
          });
        }
      });
    }

    // 判断图片是否为正方形
    function picOnLoad() {
      let img = document.querySelector(".pic>img");

      const width = img.width;
      const height = img.height;

      // 判断是否为正方形图片
      console.log(width, height);
      const isSquare = Math.abs(width / height - 1) < 0.3||width<height

      console.log(isSquare);

      proxy.picType = isSquare ? "square" : "rectangle";
    }

    return {
      confirm,
      abandonModRun,
      deleteModRun,
      picOnLoad,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../less/variables.less";
.detail {
  height: 94%;
  width: 100%;
  position: relative;
  top: 3px;
  > div {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    > .pic {
      flex: 0.8;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: #fff;
      border-radius: 5px;
      box-shadow: 2px 2px 4px 2px rgba(0, 0, 0, 0.1);
      padding: 0.5%;
      // margin-bottom: 0.5%;
      position: relative;
      overflow: hidden;
      > .controller {
        float: left;
        border-radius: 5px;
        background-color: @red;
        padding: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        position: absolute;
        left: 1%;
        top: 2%;
        z-index: 99;
        > img {
          width: 20px;
        }
      }
      > .controller:hover {
        cursor: pointer;
        background-color: #ff4d58;
      }
      > #rectangle {
        width: 100%;
        height: auto;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
      > #square {
        height: 100%;
      }
    }
    > .introduction {
      flex: 0.1;
      display: flex;
      align-items: center;
      > * {
        margin: 0.5% 0;
      }
      > .title {
        font-size: 180%;
        font-weight: bold;
        display: flex;
        align-items: center;
        > * {
          margin: 0 10px;
        }
        > div:first-child {
          background-color: @red;
          height: 32px;
          width: 7px;
          border-radius: 7px;
          margin-left: 0%;
        }
        > .tag {
          font-size: 50%;
          font-weight: normal;
          color: @red;
          padding: 5px 10px;
          background-color: #fff;
          border: @red solid 1px;
          border-radius: 5px;
          font-weight: bold;
          margin-right: 0;
          display: flex;
          align-items: center;
          > img {
            width: 15px;
            margin-right: 5px;
          }
        }
      }
    }
    > .ModController {
      flex: 0.1;
      display: flex;
      align-items: center;
      > div {
        background-color: transparent;
        > button {
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          padding: 20px;
          border-radius: 5px;
          font-size: 100%;
          box-shadow: @box-shadow;
          > span {
            font-size: 150% !important;
            > img {
              width: 20px;
              margin-right: 5px;
            }
          }
        }
      }
      > div:hover {
        cursor: pointer;
      }
      > .abandonModRun {
        margin-right: 1%;
        > button {
          background-color: @blue;
        }
      }
      > .deleteModRun {
        > button {
          background-color: @green;
        }
      }
    }
  }
}

.detail-col {
  display: flex;
  align-content: center;
  margin-top: 0.5%;
  > .pic {
    width: 45%;
    padding: 1% 0.5%;
  }
  > .introduction {
    width: 45%;
    margin-left: 0.5%;
  }
}
</style>